package com.quan.sdk.weixin.tools;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.mzlion.easyokhttp.HttpClient;
import com.quan.sdk.weixin.common.WeixinContext;
import com.quan.sdk.weixin.model.JsTicket;

/**
 * AccessToken工具类
 * @author yhaoquan
 *
 */
public class JsApiTicketTools {
	
	private static Logger logger = LoggerFactory.getLogger(JsApiTicketTools.class);
	
	/**
	 * JsApi_Ticket 票据
	 * <br>方式：GET
	 * <br>参数：
	 * <br>&nbsp;&nbsp;&nbsp; access_token 全局唯一接口调用凭据
	 * <br>&nbsp;&nbsp;&nbsp; type
	 */
	public static String JS_API_TICKET_URL = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=%s&type=%s" ;

	/**
	 * 获取JS-SDK的JSAPI-TICKET票据
	 * @param accessToke 全局唯一接口调用凭据AccessToken
	 * @param jsApiType 票据类型（jsapi:用于分享等js-api,wx_card用于卡券接口签名凭证api_ticket）默认为jsapi
	 * @return
	 */
	public static JsTicket getJsApiTicket(String accessToke, JsApiType jsApiType) {
		if(StringUtils.isEmpty(accessToke)) {
			accessToke = WeixinContext.getAccessToken() ;
		}
		if(StringUtils.isEmpty(accessToke)) {
			logger.info("获取JS-SDK的JSAPI-TICKET需要微信全局唯一凭证AccessToken");
			return null;
		}
		
		String url = String.format(JS_API_TICKET_URL, accessToke, null == jsApiType ? JsApiType.jsapi.name() : jsApiType.name()) ;
		JsTicket ticket = HttpClient.get(url).execute().asBean(JsTicket.class) ;
		if(null != ticket) {
			if (ticket.getErrcode() == 0) {
				logger.info("JSAPI-TICKET：【{}】", ticket.getTicket());
				//保存到全局缓存中，方便接口调用
				WeixinContext.setJsApiTicket(ticket.getTicket());
			} else {
				logger.error("JS-SDK的JsTicket获取失败，错误原因：{}", ticket.getErrmsg());
			}
		} else {
			logger.error("JS-SDK的JsTicket获取失败，请检查API地址是否正确：{}", url);
		}
		
		return ticket ;
	}
	
	/**
	 * 获取JS-SDK的JSAPI-TICKET票据，默认为JSAPI
	 * @return
	 */
	public static JsTicket getAccessToken() {
		return getJsApiTicket(null, null) ;
	}
	
	/**
	 * JSApi的类型
	 * <br>jsapi: 用于分享等js-api
	 * <br>wx_card：用于卡券接口签名凭证api_ticket
	 */
	public enum JsApiType {
		jsapi, wx_card
	}
	
}
